﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StuWebApi.Dto;
using StuWebApi.Entity;

namespace StuWebApi.Controllers;

[ApiController]
[Route("[controller]")]
public class ClassroomsController : ControllerBase 
{
    private readonly ApplicationDbContext _context;

    public ClassroomsController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Classroom>>> GetClassrooms()
    {
        return await _context.Classrooms.Include(c => c.School).ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<Classroom>> GetClassroom(int id)
    {
        var classroom = await _context.Classrooms.Include(c => c.School)
            .FirstOrDefaultAsync(c => c.ClassroomId == id);

        if (classroom == null)
        {
            return NotFound();
        }

        return classroom;
    }

    [HttpPost]
    public async Task<ActionResult<Classroom>> PostClassroom(ClassroomDto classroomDto)
    {
        var classroom = new Classroom
        {
            Name = classroomDto.Name,
            SchoolId = classroomDto.SchoolId
        };

        _context.Classrooms.Add(classroom);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetClassroom), new { id = classroom.ClassroomId }, classroom);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> PutClassroom(int id, ClassroomDto classroomDto)
    {
        var classroom = await _context.Classrooms.FindAsync(id);
        if (classroom == null)
        {
            return NotFound();
        }

        classroom.Name = classroomDto.Name;
        classroom.SchoolId = classroomDto.SchoolId;

        _context.Entry(classroom).State = EntityState.Modified;
        await _context.SaveChangesAsync();

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteClassroom(int id)
    {
        var classroom = await _context.Classrooms.FindAsync(id);
        if (classroom == null)
        {
            return NotFound();
        }

        _context.Classrooms.Remove(classroom);
        await _context.SaveChangesAsync();

        return NoContent();
    }
}
